﻿using BLL.CodeManage;
using Common;
using Model.CodeManage;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace DAGG.Controllers
{
    public class DownLoadController : BaseController
    {
        GenCodeBLL bll = new GenCodeBLL();
        //
        // GET: /DownLoad/
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取生码文件
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportCode(int BatchId, string key, string companyName)
        {
            //获取该批次的生码类型
            GenCodeModel model = bll.GetModelByBatch(BatchId);
            string queryField = string.Empty;//需要查询的字段标记
            if (model != null)
            {
                string[] strType = model.CodeType.Split(',');
                foreach (string codeType in strType)
                {
                    if (codeType.Contains("1"))
                    {//防伪码
                        queryField += "Fw_Code,";
                    }
                    if (codeType.Contains("2"))
                    {//管理码
                        queryField += "Wl_Code,";
                    }
                    
                }
               //// string fileUrl = ExportCodeByBatch(BatchId, queryField,model.EnterpriseCode);
                string fileUrl = ExportCodeByBatch(BatchId, queryField, model.Code);
                //string companyName = fileUrl.Split('^')[1];
               return File(new FileStream(fileUrl.Split('^')[0], FileMode.Open), "application/octet-stream", Server.UrlEncode(companyName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"));
             
            }
            return null;
        }

        private string ExportCodeByBatch(int BatchId, string queryField, string EnterpriseCode)
        {

            GenCodeBatchBLL bll = new GenCodeBatchBLL();
            GenCodeBatch model = bll.getModel(BatchId);
            string batch = model.Batch;//获取生码批次
            string companyId = model.EnterpriseId.ToString();


            string txtfilePath = AppConst.Path + EnterpriseCode + batch + AppConst.TxtSuffix;
            FileOperation.DropToFile(txtfilePath);

            //获取对应的datatable
            DataTable codeTbl = bll.queryCode(AppConst.TablePrefix + EnterpriseCode+batch, queryField);
            bool fwIsExist = false;
            bool wlIsExist = false;
            // bool jfIsExist = false;
            //列名判断
            for (int i = 0; i < codeTbl.Columns.Count; i++)
            {
                var columnName = codeTbl.Columns[i].ColumnName;
                if (columnName == "Fw_Code")
                    fwIsExist = true;
                if (columnName == "Wl_Code")
                    wlIsExist = true;
               
            }

            //写入txt文件
            string newPath = AppConst.Path + "档案馆" + EnterpriseCode+ batch + AppConst.TxtSuffix;
            string key = AppConst.DigitCodeKey;
            FileStream fs = new FileStream(newPath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            string overrideLine = string.Empty;
            foreach (DataRow dr in codeTbl.Rows)
            {
                overrideLine = string.Empty;
                if (fwIsExist)
                    overrideLine += MiMa.Jiami(dr["Fw_Code"].ToString(), key);
                if (wlIsExist)
                    overrideLine += "," + dr["Wl_Code"].ToString() + ",";
                overrideLine = overrideLine.TrimEnd(',');
                //开始写入
                sw.WriteLine(overrideLine);
            }
            sw.Flush();
            fs.Close();
            GC.Collect();
            return newPath + "^" + "档案馆";
        }


	}
}